<template>
  <div class="user-management-container">
    <el-row :gutter="20">
      <el-col :span="7">
        <el-form :inline="false" class="form-container">
          <el-form-item>
            <el-select class="full-width-select" v-model="skuIdList" placeholder="请选择SKU" multiple filterable>
              <el-option v-for="(item,key) in skuList" :value="item.id" :key="key"
                         :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="12">
                <el-button class="full-width-button" icon="el-icon-search" type="primary" @click="fetchTree">
                  查询SKU
                </el-button>
              </el-col>
              <el-col :span="12">
                <el-button class="full-width-button" icon="el-icon-plus" type="success" @click="handleEdit">新建BOM工单</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-card style="height:calc(80vh - 30px);overflow-y:auto">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            v-loading="listLoadingTree"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <i :class="data.icon"></i> <!-- 图标 -->
                <el-tooltip :content="node.label" placement="top-start" effect="dark"
                            :disabled="getTooltipContent(node.label)">
                  <span class="node-label">{{ node.label }}</span> <!-- 节点文本 -->
                </el-tooltip>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            @selection-change="setSelectRows"
          >
            <el-table-column align="center" show-overflow-tooltip type="selection"/>
            <el-table-column align="center" label="序号" width="55">
              <template #default="{ $index }">
                {{ total - (queryForm.pageNo - 1) * queryForm.pageSize - $index }}
              </template>
            </el-table-column>
            <el-table-column prop="no" label="批次号" align="center"/>
            <el-table-column label="实拍图片" align="center" width="80">
              <template #default="{row}">
                <el-image :src="fileRootPath+row.pic" @click="imgPreview($event)" v-if="row.pic"/>
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="BOM工单编码" align="center"/>
            <el-table-column prop="production_date" label="生产日期" align="center"/>
            <el-table-column prop="creator.nickname" label="创建人" align="center" width="80"/>
            <el-table-column prop="update_time" label="创建/修改时间" align="center" width="160"/>
            <el-table-column prop="update_time" label="上级SKU" align="center">
              <template #default="{row}">{{ row.parentSku.label }}</template>
            </el-table-column>
            <el-table-column
              label="操作"
              show-overflow-tooltip
              width="180"
              align="left" header-align="center"
            >
              <template #default="{ row }">
                <el-button circle icon="el-icon-view" plain @click="handleShow(row)" type="success"/>
                <el-button circle icon="el-icon-edit" plain @click="handleEdit(row)" type="primary"/>
                <el-button circle icon="el-icon-delete" plain @click="handleDelete(row)" type="danger"/>
                <el-button circle icon="el-icon-link" plain @click="handleLink(row)" type="info"/>
              </template>
            </el-table-column>
            <template #empty>
              <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
          <edit ref="edit" @fetch-data="fetchAll"/>
          <el-image-viewer v-if="imgPreviewVisible" :url-list="imgSrc" :on-close="imgPreviewClose"/>
        </el-card>
      </el-col>

    </el-row>
  </div>
</template>

<script>
import {doDelete, getList, recursionList as getRecursionList} from '@/api/bom/bom'
import Edit from './components/BomEdit'
import {parseTime} from '@/utils/index'
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import {all as getSkuList} from "@/api/sku/classify";


export default {
  name: 'bomOrder',
  components: {Edit, ElImageViewer},
  filters: {
    parseTime: parseTime,
    statusFilter(status) {
      const statusMap = {
        1: 'danger',
        2: 'success',
        3: 'primary',
        4: 'info',
        5: 'warning',
        6: '',
      }
      return statusMap[status]
    },
    readFilter(status) {
      const statusMap = {
        1: '文本',
        2: '枚举',
        3: '日期',
        4: '数字',
        5: '百分比',
        6: '附件',
      }
      return statusMap[status]
    },
  },
  data() {
    return {

      skuList: [],
      skuIdList:[],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      treeData: [
        {
          label: '一级 1',
          icon: 'el-icon-folder', // 图标类名
          children: [
            {
              label: '二级 1-1',
              icon: 'el-icon-document', // 图标类名
              children: [
                {
                  label: '三级 1-1-1',
                  icon: 'el-icon-document', // 图标类名
                },
              ],
            },
          ],
        },
        {
          label: '一级 2',
          icon: 'el-icon-folder', // 图标类名
          children: [
            {
              label: '二级 2-1',
              icon: 'el-icon-document', // 图标类名
            },
            {
              label: '二级 2-2',
              icon: 'el-icon-document', // 图标类名
            },
          ],
        },
      ],
      imgPreviewVisible: 0,
      list: [],
      listLoading: true,
      listLoadingTree: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        sku_id: 0,
      },
      imgSrc: [],
    }
  },
  created() {
    this.fileRootPath = process.env.VUE_APP_FILE_ROOT_PATH
    this.fetchAll()
  },
  methods: {
    getTooltipContent(label) {
      const maxLength = 30; // 设置最大长度，超过这个长度时显示 tooltip
      if (label.length > maxLength) {
        return false;
      } else
        return true; // 如果文本长度不超过 maxLength，返回空字符串，不显示 tooltip
    },
    imgPreviewClose() {
      this.imgPreviewVisible = 0
      this.imgSrc.pop()
    },
    imgPreview(event) {
      var el = event.currentTarget
      this.imgPreviewVisible = 1
      this.imgSrc.push(el.src)
    },
    toView(row) {
      this.$router.push({path: '/finance/income', query: {Mold_id: row.id}})
    },
    setSelectRows(val) {
      this.selectRows = val
    },
    handleEdit(row) {
      if (row.id) {
        this.$refs['edit'].showEdit(row)
      } else {
        this.$refs['edit'].showEdit(null)
      }
    },
    handleLink(row) {
      var info = {
        'level': row.level,
        'sku_id': row.sku_id,
        'parent_id': row.parent_id,
        'attribute_spec': row.attribute_spec,
        'attribute_name': row.attribute_name,
        'parent_sku_id': row.parent_sku_id,
        'children': row.children,
        'is_link': 1,
        'parentSku': row.parentSku,
      }
      info.children.forEach(item => {
        delete item.id;   // 删除 id 属性
        item.weight = 0; // 删除 weight 属性
      });
      this.$refs['edit'].showEdit(info)
    },
    handleShow(row) {
      this.$refs['edit'].viewEdit(row)
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const {msg} = await doDelete({ids: row.id})
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          await this.fetchData()
          await this.fetchTree()
        })
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join()
          this.$baseConfirm('你确定要删除选中项吗', null, async () => {
            const {msg} = await doDelete({ids})
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
            await this.fetchTree()
          })
        } else {
          this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
        }
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.pageNo = 1
      this.fetchData()
    },
    async fetchData() {
      this.listLoading = true
      const {
        data: {list, total},
      } = await getList(this.queryForm)
      this.list = list
      this.total = total
      this.listLoading = false
    },
    async fetchTree() {
      this.listLoadingTree = true
      const {
        data: {treeData},
      } = await getRecursionList({'sku_id':this.skuIdList})
      this.treeData = treeData
      this.listLoadingTree = false
    },
    handleNodeCollapse(data, node, event) {
      data.icon = 'el-icon-folder'
      this.$set(data, 'expand', true)
    },
    handleNodeExpand(data, node, event) {
      data.icon = 'el-icon-folder-opened'
      this.$set(data, 'expand', false)
    },
    handleNodeClick(data, node, event) {
      // node: 节点对象
      // data: 节点对应的数据
      // event: 原生点击事件
      // console.log('Node clicked:', node);
      // console.log('Data:', data);
      // console.log('Event:', event);
      // 你可以在这里处理点击事件的逻辑
      if (data.expand === false) {
        getRecursionList({'parent_sku_id': data.sku_id}).then(response => {
          this.$set(data, 'children', response.data.treeData);
          this.$set(data, 'expand', true)
          node.expand(this.getTrue)
          data.icon = 'el-icon-folder-opened'
        });
      } else {
        this.$set(data, 'expand', false)
        data.icon = 'el-icon-folder'
      }
      this.queryForm.sku_id = data.sku_id
      this.fetchData()

    },
    getTrue() {
      return true
    },
    fetchAll() {
      getSkuList({pageNo: 'all'}).then(response => {
        this.skuList = response.data.list
      });
      this.fetchData()
      this.fetchTree()
    }
  },
}
</script>
<style scoped>
.button-container {
  text-align: center; /* 水平居中按钮 */
  margin-bottom: 10px; /* 与树形结构之间留一些间距 */
}

.full-width-button {
  width: 98%; /* 按钮宽度与父容器相同 */
  display: inline-block; /* 使按钮可以水平居中 */
}
.full-width-select {
  width: 100%; /* 按钮宽度与父容器相同 */
  display: inline-block; /* 使按钮可以水平居中 */
}

/* 树形节点的样式，如果需要调整可以在这里添加 */
.custom-tree-node {
  display: flex;
  align-items: center;
}

.custom-tree-node i {
  margin-right: 8px;
}

.node-label {
  /* 设置宽度限制，确保文本超出时显示省略号 */
  display: inline-block;
  max-width: 400px; /* 根据实际需求调整宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: top;
}
</style>
